/**
 * 区域奖励算法
 */
const calcReward = async function(data) {
	let userRewardList = [];

	let {
		orderInfo, // 订单信息
		userInfo, // 下单人信息
		mchInfo, // 商家配置信息
	} = data;
	let { goods_sku_list } = orderInfo;
	if (orderInfo.order_type !== 0) {
		// 只有实物商品才有区域奖励
		return [];
	}
	let province = orderInfo.express_info.position.province.name; // 省
	let city = orderInfo.express_info.position.city.name; // 市
	let area = orderInfo.express_info.position.area.name; // 区
	console.log(`订单所属区域: ${province}/${city}/${area}`)

	// 获取区域代理列表(省代、市代、区代)
	let agentList = await vk.daoCenter.fxRegionalAgentDao.listByAddress(orderInfo.express_info.position);

	console.log('区域代理人列表: ', agentList, agentList.length)

	// 求出该订单一共给哪些人各发放多少区域奖励，同时求出对应的商品奖励明细
	// 循环区域代理人
	for (let i = 0; i < agentList.length; i++) {
		let agentItem = agentList[i];
		if (!agentItem.reward_rule.is_calc) {
			continue;
		}
		let sumUserReward = 0; // 该用户总奖励
		let goods_reward_list = []; // 商品奖励明细
		// 循环商品
		for (let j = 0; j < goods_sku_list.length; j++) {
			let goodsItem = goods_sku_list[j];
			let {
				reward_rule = {}, // 奖励规则
					should_payment_amount, // 应付金额
					buy_num, // 购买数量
			} = goodsItem;
			if (reward_rule.is_custom === -1) {
				// 无奖励
				continue;
			}
			let k = 1; // 比例
			// 判断该商品是否有自定义倍数
			if (reward_rule.is_custom === 1) {
				k = reward_rule.regional_reward_multiple;
			}
			if (k < 0) k = 0;

			let goodsReward = {
				sku_id: goodsItem._id,
				goods_id: goodsItem.goods_id,
				buy_num: goodsItem.buy_num,
				should_payment_amount: goodsItem.should_payment_amount,
				reward_value: 0, // 奖励金额（分为单位）
				reward_value_format: 0, // 奖励金额（元为单位）
				reward_formula: "", // 计算公式（元为单位）
			};
			if (agentItem.reward_rule.is_fixed_calc) {
				// 固定金额
				goodsReward.reward_value = vk.pubfn.toDecimal(buy_num * agentItem.reward_rule.fixed_value * k, 0);
				goodsReward.reward_value_format = vk.pubfn.toDecimal(goodsReward.reward_value / 100, 2);
				goodsReward.reward_formula = `${buy_num} * ${vk.pubfn.toDecimal(agentItem.reward_rule.fixed_value / 100, 2)} * ${k} = ${goodsReward.reward_value_format}`;
			} else {
				// 百分比金额
				goodsReward.reward_value = vk.pubfn.toDecimal(should_payment_amount * agentItem.reward_rule.proportion_value * k, 0);
				goodsReward.reward_value_format = vk.pubfn.toDecimal(goodsReward.reward_value / 100, 2);
				goodsReward.reward_formula =
					`${vk.pubfn.toDecimal(should_payment_amount / 100, 2)} * ${agentItem.reward_rule.proportion_value} * ${k} = ${goodsReward.reward_value_format}`;
			}
			// 如果该商品实付金额小于奖励支出，为了商家利益，此商品不返佣
			if (goodsItem.should_payment_amount >= goodsReward.reward_value) {
				goods_reward_list.push(goodsReward);
				sumUserReward += goodsReward.reward_value; // 已分为单位
			}
		}

		let reward_name = "";
		if (agentItem.lv === 1) {
			reward_name = `省代-${province}`;
		} else if (agentItem.lv === 2) {
			reward_name = `市代-${province}-${city}`;
		} else if (agentItem.lv === 3) {
			if (province == city) {
				reward_name = `区代-${province}-${area}`;
			} else {
				reward_name = `区代-${province}-${city}-${area}`;
			}
		}
		let calc_amount = orderInfo.amount_info.payment_amount - orderInfo.amount_info.express_amount; // 付款金额，去除运费
		// 只有订单商品合计付款金额 > 0，且奖励 > 0 才添加
		if (calc_amount > 0 && sumUserReward > 0) {
			userRewardList.push({
				user_id: agentItem.user_id, // 奖励归属人id
				reward_value: vk.pubfn.toDecimal(sumUserReward, 0), // 该用户总奖励（已分为单位）
				reward_value_format: vk.pubfn.toDecimal(sumUserReward / 100, 2), // 该用户总奖励（以元为单位）
				goods_reward_list, // 各商品奖励明细
				reward_type: 2, // 0: 未分类奖励 1:二级分销  2:区域奖励
				reward_name,
				calc_rule: {
					calc_amount: vk.pubfn.toDecimal(calc_amount / 100, 2), // 付款金额，去除运费
					reward_value: vk.pubfn.toDecimal(sumUserReward / 100, 2),
					k: calc_amount > 0 ? vk.pubfn.toDecimal(sumUserReward / calc_amount , 6):0,
				}
			});
		}
	}

	return userRewardList;
};

module.exports = calcReward;
